import type { PlatformTypeValue } from '../../../../../../types/interfaces'
import type {
  AutoPagination,
  IPaginationOptions,
  IPaginationSelectors,
} from '../../index'
import { BAIDU_RESULT_BASE_SELECTOR } from '../../../../../../lib/page_handler/platform/baidu/types'
import { BIAN_PAGINATION_CONFIG } from '../../../../../../lib/page_handler/platform/bian/types'
import { GITEE_PAGINATION_CONFIG } from '../../../../../../lib/page_handler/platform/gitee/types'
import { GITHUB_PAGINATION_CONFIG } from '../../../../../../lib/page_handler/platform/github/types'
import { GreasyForkPageType } from '../../../../../../lib/page_handler/platform/greasyfork/types'
import { ToolKit } from '../../../../../../lib/utils/toolkit'
import {
  BAI_DU_BASE_URL,
  logger,
  SUPPORTED_PLATFORMS,
} from '../../../../../../types/constants'
import { GiteeSearchParams } from '../../platform/gitee'
import { GithubSearchParams } from '../../platform/github'
import { GreasyForkSearchParams } from '../../platform/greasy_fork'

export interface IPaginationPlatformConfig {
  className: {
    previousPage: string
    nextPage: string
    currentPage: string
    allPage: string
  }
  childSelector: {
    previousPage: string
    nextPage: string
    currentPage: string
    allPage: string
  }
  selector: {
    container: string
    previousPage: string
    nextPage: string
    currentPage: string
    item: string
    link: string
  }
  list: IPaginationSelectors
}

export const PAGINATION_CONFIG: Partial<Record<PlatformTypeValue, IPaginationOptions>> = {
  [SUPPORTED_PLATFORMS.BAI_DU]: {
    selectors: { container: '#content_left', item: `#content_left > ${BAIDU_RESULT_BASE_SELECTOR}` },
    pageNum: (instance: AutoPagination) => instance.configService.getPageNumSelector(),
    pageItemLink: (instance: AutoPagination) => instance.baiduService.getPageItemLinkSelector(),
    nextPageUrl: (instance: AutoPagination, currentPage: number) => {
      const selector = instance.configService.getPageSelector()
      const $textarea = $(selector)

      if (!$textarea || $textarea.length === 0) {
        logger.warn(`[${instance.name}] 搜索关键词获取失败，选择器：${selector}`)
        return null
      }

      const searchKeyword = $textarea.val() as string

      if (!searchKeyword) {
        logger.info(`[${instance.name}] 搜索关键词为空，取消加载`)
        return null
      }

      const linkParams = instance.baiduService.getUsmFromPageItemLink(instance)
      const params = instance.generateUrlParams(linkParams, searchKeyword, currentPage)

      return `${BAI_DU_BASE_URL}/s?${new URLSearchParams(params).toString()}`
    },
  },
  [SUPPORTED_PLATFORMS.GREASY_FORK]: {
    selectors: (instance: AutoPagination) => {
      switch (instance.pageType) {
        case GreasyForkPageType.SCRIPT_LIST:
          return { container: '#browse-script-list', item: '#browse-script-list > li' }
        case GreasyForkPageType.SCRIPT_VERSIONS:
          return { container: '.history_versions', item: '.history_versions > li' }
        case GreasyForkPageType.SCRIPT_FEEDBACK:
          return { container: '.script-discussion-list', item: '.script-discussion-list > .discussion-list-container' }
      }

      return {} as IPaginationSelectors
    },
    pageNum: (instance: AutoPagination) => instance.configService.getPageNumSelector(),
    pageItemLink: (instance: AutoPagination) => instance.greasyForkService.getPageItemLinkSelector(),
    nextPageUrl: (instance: AutoPagination, currentPage: number) => {
      const selector = instance.configService.getPageSelector()
      const $paginationNextBtn = $(selector)

      if (!$paginationNextBtn || $paginationNextBtn.length === 0) {
        logger.warn(`[${instance.name}] [分页组件] 下一页按钮获取失败`, selector)
        return null
      }

      const url = $paginationNextBtn.attr('href') || ''
      const fullUrl = ToolKit.browser.url.getFullUrl(url)

      return ToolKit.browser.url.replaceUrlParam(fullUrl, GreasyForkSearchParams.Page, currentPage) || null
    },
  },
  [SUPPORTED_PLATFORMS.BIAN]: {
    selectors: BIAN_PAGINATION_CONFIG.list,
    pageNum: (instance: AutoPagination) => instance.configService.getPageNumSelector(),
    pageItemLink: (instance: AutoPagination) => instance.bianService.getPageItemLinkSelector(),
    nextPageUrl: (instance: AutoPagination, currentPage: number) => {
      const selector = instance.configService.getPageSelector()
      const $paginationNextBtn = $(selector)

      if (!$paginationNextBtn || $paginationNextBtn.length === 0) {
        logger.warn(`[${instance.name}] [分页组件] 下一页按钮获取失败`, selector)
        return null
      }

      const url = $paginationNextBtn.attr('href') || ''
      const fullUrl = ToolKit.browser.url.getFullUrl(url)
      const nextPageUrl = fullUrl.replace(/index_(\d+)\.html/, `index_${currentPage}.html`)

      return nextPageUrl || null
    },
  },
  [SUPPORTED_PLATFORMS.GITEE]: {
    selectors: GITEE_PAGINATION_CONFIG.list,
    pageNum: (instance: AutoPagination) => instance.configService.getPageNumSelector(),
    pageItemLink: (instance: AutoPagination) => instance.giteeService.getPageItemLinkSelector(),
    nextPageUrl: (instance: AutoPagination, currentPage: number) => {
      const selector = instance.configService.getPageSelector()
      const $paginationNextBtn = $(selector)

      if (!$paginationNextBtn || $paginationNextBtn.length === 0) {
        logger.warn(`[${instance.name}] [分页组件] 下一页按钮获取失败`, selector)
        return null
      }

      const url = $paginationNextBtn.attr('href') || ''
      const fullUrl = ToolKit.browser.url.getFullUrl(url)

      return ToolKit.browser.url.replaceUrlParam(fullUrl, GiteeSearchParams.Page, currentPage) || null
    },
  },
  [SUPPORTED_PLATFORMS.GITHUB]: {
    selectors: GITHUB_PAGINATION_CONFIG.list,
    pageNum: (instance: AutoPagination) => instance.configService.getPageNumSelector(),
    pageItemLink: (instance: AutoPagination) => instance.githubService.getPageItemLinkSelector(),
    nextPageUrl: (instance: AutoPagination, _currentPage: number) => {
      const selector = instance.configService.getPageSelector()
      const $paginationNextBtn = $(selector)

      if (!$paginationNextBtn || $paginationNextBtn.length === 0) {
        logger.warn(`[${instance.name}] [分页组件] 下一页按钮获取失败`, selector)
        return null
      }

      const url = $paginationNextBtn.attr('href') || ''
      const fullUrl = ToolKit.browser.url.getFullUrl(url)

      // 最小版本作为下一页的参数
      const pageMinVersion = $(instance.selectors.item).last().find('.Details h2 > a').text().trim() || ''

      return ToolKit.browser.url.replaceUrlParam(fullUrl, GithubSearchParams.After, pageMinVersion) || null
    },
  },
}
